from flask import Flask
from flask import render_template
from jinja2 import Markup, Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig

# 关于 CurrentConfig，可参考 [基本使用-全局变量]
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

from pyecharts import options as opts
from pyecharts.charts import Line,Pie, Timeline
from pyecharts.faker import Faker

import pandas as pd
import requests,requests_html
import os
from glob import glob 
from lxml import etree

import random  #测试

app = Flask(__name__, static_folder="static")



#########################以下代码可以替换


# x_data = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# y_data = [820, 932, 901, 934, 1290, 1330, 1320]
###########################
data = pd.read_csv('C:\\Users\\zjl\\Desktop\\Python数据分析\\期末项目\\AI_BD_媒介融合\\datasets\\Combined_374.tsv', sep='\t', encoding="utf8")


data_to_y = data['YR'].value_counts()

y_data = data_to_y.values.tolist()
y_data.sort(reverse=False)

data_by_time = data.sort_values(by=['YR'], ascending=False)
data_to_x = data_by_time['YR'].drop_duplicates(keep='first',inplace=False)
x_data_int = data_to_x.values.tolist()
x_data_int.sort(reverse=False)
x_data = []
for i in x_data_int:
    j = str(i)+"年"
    x_data.append(j)

#-------------------------------------------------------
def Line_base() :
    c = (
        Line()
        .set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=False),
            xaxis_opts=opts.AxisOpts(type_="category"),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
        )
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(

            series_name="发文数",
            y_axis=y_data,
            symbol="emptyCircle",
            is_symbol_show=True,
            label_opts=opts.LabelOpts(is_show=False),
    )
        .render("./templates/Line.html")
    )

    return c



#############################################

df_to_source = data
df_source = df_source = df_to_source["来源"].value_counts()
a = df_source.index
type_source = a.tolist()
count_source = df_source.tolist()

source_rate=[]
for i in range(0,len(count_source)):
    j = str(count_source[i]/374)+'%'
    source_rate.append(j)


#-------------------------------------------------------
def Pie_base() :
    p = (
        Pie()
        .add("", [list(z) for z in zip(type_source, count_source)],center=['50%', '50%'],radius="55%")
        .set_global_opts(title_opts=opts.TitleOpts(title="文献来源期刊分布",pos_left="center",pos_top="20"),legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%", orient="vertical"))

        # .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        .set_series_opts(
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{b}: {c} ({d}%)"
        ))
        .render("./templates/pie.html")

        
        )

    return p
##########################################


#-------------------------------------------------------


def Timeline_base() :
    name = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    value = [random.randint(100, 1000) for _ in range(6)]
    one = Pie()
    two = Pie()
    three = Pie()

    four = Pie()
    timeline = Timeline(),

    t = (
        
        one.add("", name, [random.randint(100, 1000) for _ in range(6)],
                        radius=[40, 80],                
                        label_text_color=None,                
                        is_label_show=True,                
                        legend_orient='vertical',                
                        legend_pos='left'),
         
        
        two.add("", name, [random.randint(100, 1000) for _ in range(6)],
                        radius=[40, 80],                
                        label_text_color=None,                
                        is_label_show=True,                
                        legend_orient='vertical',                
                        legend_pos='left'),
         
        
        three.add("", name, [random.randint(100, 1000) for _ in range(6)], 
                          radius=[40, 80],   
                          label_text_color=None,                  
                          is_label_show=True,                  
                          legend_orient='vertical',                  
                          legend_pos='left'),
         
        
        four.add("", name, [random.randint(100, 1000) for _ in range(6)],
                         radius=[40, 80],                 
                         label_text_color=None,                 
                         is_label_show=True,                 
                         legend_orient='vertical',                 
                         legend_pos='left'),
         
        timeline.add(one,two,three,four),
        timeline.render("timeline.html"),
        
        
        ),
    
        
        
        
    return t

#
###########################################
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/time")
def index_time():
    return render_template("Line.html")


@app.route("/source")
def index_source():
    p = Pie_base()
    # return Markup(p.render_embed())
    return render_template("pie.html")
    
@app.route("/keyword")
def index_keyword():
    return render_template("timeline.html")


if __name__ == "__main__":
    app.run()